<?php

/**
 * WeChat SDK
 * @author xz
 * @version 1.0 2014-07-29
 */

// require_once(PATH_APPLICATION . 'Component/php/SocketLog.class.php');

class Wechat
{
    // API URL
    public static $apiUrlHttp = 'https://api.weixin.qq.com/cgi-bin/';
    public static $apiUrlHttps = 'https://api.weixin.qq.com/cgi-bin/';
    public static $uploadMediaUrl = 'http://file.api.weixin.qq.com/cgi-bin/media/upload';
    public static $uploadNewsUrl = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews';
    
    // Debug
    public static $debug = false;

    // access_token
    public static $access_token;
    

    function __construct($access_token) {
        self::$access_token = $access_token;
    }

    
    public static function callapi($command, $params = array(), $method = 'GET', $multi = false)
    {
        
        $url = self::$apiUrlHttps.trim($command, '/') . '?access_token=' . self::$access_token;
        
        //
        $result = Http::request($url, $params, $method, $multi);
        $result = preg_replace('/[^\x20-\xff]*/', "", $result);
        $result = iconv("utf-8", "utf-8//ignore", $result);
        
        if (self::$debug) {
            echo '<pre>';
            echo 'API:'.$url;
            echo '<br>Parameters:<br>';
            var_dump($params);
            echo 'Response:'.$result;
            echo '</pre>';
        }

        return json_decode($result, true);
    }


    public function uploadMedia($media, $type)
    {
        $url = self::$uploadMediaUrl . '?access_token=' . self::$access_token . '&type=' . $type;

        $params = array(
                    'media' => $media
                );


        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($curl);
        $e = curl_error($curl);
        curl_close($curl);

        return $output;

    }


    public function uploadNews($articles)
    {
        $url = self::$uploadNewsUrl . '?access_token=' . self::$access_token;

        $params = array(
                    'articles' => $articles
                );


        // slog('What will upload to WeChat:');
        // slog(urldecode(json_encode($params)));
        
        $headers=array();
        if(isset($_SERVER['HTTP_USER_AGENT']))
        {
            $headers[]='User-Agent: '.$_SERVER['HTTP_USER_AGENT'];
        }
        if(isset($_SERVER['HTTP_SOCKETLOG']))
        {
            $headers[]='Socketlog: '.$_SERVER['HTTP_SOCKETLOG'];
        }
        

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headers); 

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, urldecode(json_encode($params)));
        
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($curl);
        $e = curl_error($curl);
        curl_close($curl);

        return $output;
    }
}


/**
 * Token
 */

class WechatToken
{
    public static $access_token_url = '';
    public static $appId = '';
    public static $secret = '';


    function __construct($appId, $secret)
    {
        self::$appId = $appId;
        self::$secret = $secret;
        self::$access_token_url = sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", $appId, $secret);
    }

    public function getAccessToken()
    {
        $responseJson = Http::request(self::$access_token_url);

        return $responseJson;
    }
}


/**
 * HTTP Request Class
 */

class Http
{
    /**
     * 发起一个HTTP/HTTPS的请求
     * @param $url 接口的URL 
     * @param $params 接口参数   array('content'=>'test', 'format'=>'json');
     * @param $method 请求类型    GET|POST
     * @param $multi 图片信息
     * @param $extheaders 扩展的包头信息
     * @return string
     */
    public static function request( $url , $params = array(), $method = 'GET' , $multi = false, $extheaders = array())
    {
        if(!function_exists('curl_init')) exit('Need to open the curl extension');
        $method = strtoupper($method);
        $ci = curl_init();
        //curl_setopt($ci, CURLOPT_USERAGENT, 'PHP-SDK OAuth2.0');
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ci, CURLOPT_TIMEOUT, 3);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ci, CURLOPT_HEADER, false);
        $headers = (array)$extheaders;
        // echo "\n<br>What SNSGW send to/get from WeChat:<br>\n";
        switch ($method)
        {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                if (!empty($params))
                {
                    if($multi)
                    {
                        foreach($multi as $key => $file)
                        {
                            $params[$key] = '@' . $file;
                        }
                        curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                        // echo "POST:\n";
                        // var_dump($params);
                        $headers[] = 'Expect: ';
                    }
                    else
                    {
                        if (is_string ( $params )) {
                            $strPOST = $params;
                        } else {
                            $strPOST = urldecode(json_encode($params));
                        }

                        curl_setopt($ci, CURLOPT_POSTFIELDS, $strPOST);
                        // echo "POST:\n";
                        // var_dump($strPOST);
                    }
                }
                break;
            case 'DELETE':
            case 'GET':
                $method == 'DELETE' && curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
                if (!empty($params))
                {
                    $url = $url . (strpos($url, '?') ? '&' : '?')
                        . (is_array($params) ? http_build_query($params) : $params);
                        // echo "GET:\n";
                        // var_dump($url);
                }
                break;
        }
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );
        curl_setopt($ci, CURLOPT_URL, $url);
        if($headers)
        {
            curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
        }

        $response = curl_exec($ci);
        curl_close ($ci);
        return $response;
    }
}
